package com.weiiew.backend.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

/**
 * 用于统一api调用和快捷键调用错误处理不统一问题
 *
 * @author 魏锴
 * @since 2025/5/5
 */
@Component
public class ErrorWebSocketUtil implements ApplicationContextAware {
    // 错误消息配置
    private static final String ERROR_TOPIC = "/topic/errors";
    private static final String ERROR_FORMAT = "{\"source\":\"%s\",\"message\":\"%s\"}";

    // Spring依赖
    private static ApplicationContext applicationContext;
    private static SimpMessagingTemplate messagingTemplate;

    // 私有构造函数防止实例化
    private ErrorWebSocketUtil() {
    }

    private static void initializeMessagingTemplate() {
        if (messagingTemplate == null) {
            messagingTemplate = applicationContext.getBean(SimpMessagingTemplate.class);
        }
    }

    /**
     * 发送标准错误消息
     *
     * @param source       错误来源（推荐使用"mouse"或"keyboard"）
     * @param errorMessage 错误描述信息
     */
    public static void sendError(String source, String errorMessage) {
        if (messagingTemplate != null) {
            String payload = String.format(ERROR_FORMAT, source, errorMessage);
            messagingTemplate.convertAndSend(ERROR_TOPIC, payload);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ErrorWebSocketUtil.applicationContext = applicationContext;
        initializeMessagingTemplate();
    }
}